package org.example.aigc.service.impl;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.aigc.entity.*;
import org.example.aigc.mapper.*;
import org.example.aigc.service.UserService;
import org.example.aigc.utils.Reply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    private final StudentMapper studentMapper;

    private final TeacherMapper teacherMapper;

    private final UserMapper userMapper;

    private final FavoriteMapper favoriteMapper;

    private final CourseMapper courseMapper;
    private final AudioMapper audioMapper;
    private final AppearanceMapper appearanceMapper;
    private final String uploadDir;

    @Autowired
    public UserServiceImpl(
            UserMapper userMapper,
            StudentMapper studentMapper,
            TeacherMapper teacherMapper,
            FavoriteMapper favoriteMapper,
            CourseMapper courseMapper,
            AudioMapper audioMapper,
            AppearanceMapper appearanceMapper,
            Environment environment
    ) {
        this.userMapper = userMapper;
        this.studentMapper = studentMapper;
        this.teacherMapper = teacherMapper;
        this.favoriteMapper = favoriteMapper;
        this.courseMapper = courseMapper;
        this.audioMapper = audioMapper;
        this.appearanceMapper = appearanceMapper;
        this.uploadDir = Objects.requireNonNull(environment.getProperty("spring.web.resources.static-locations")).split(":", 2)[1];
    }

    public List<Student> getAllStudent() {
        return studentMapper.selectAll();
    }

    public int hasName(String username) {
        User user = userMapper.selectByName(username);
        return user != null ? 1 : 0;
    }

    public int register(HttpServletRequest request, HttpServletResponse response, String username, String password, Boolean isStudent) {
        // 新建 user 对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setIdentity(isStudent ? 1 : 0);

        // 插入 user 数据
        userMapper.insert(user);

        // 添加 cookie
        Cookie cookie = new Cookie("userId", user.getId().toString());
        cookie.setPath("/");
        response.addCookie(cookie);
        // 将用户存入 session，方便后序获取
        request.getSession().setAttribute("user", user);

        // 插入学生或教师数据
        if (isStudent) {
            studentMapper.insert(user.getId());
        } else {
            teacherMapper.insert(user.getId());
        }
        return 0;
    }

    public Reply login(HttpServletRequest request, HttpServletResponse response, String username, String password) {
        User user = userMapper.selectByName(username);
        if (user == null) {
            return new Reply("用户登录").error(1, "用户名不存在");
        }
        if (Objects.equals(password, user.getPassword())) {
            // 添加 cookie
            Cookie cookie = new Cookie("userId", user.getId().toString());
            cookie.setPath("/");
            response.addCookie(cookie);

            // 将用户存入 session，方便后序获取
            request.getSession().setAttribute("user", user);

            return new Reply("用户登录").ok(0, "成功").put("identity", user.getIdentity());
        } else {
            return new Reply("用户登录").error(2, "密码错误");
        }
    }

    public int favorite(HttpServletRequest request, HttpServletResponse response, Long courseId) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return 1;
        }
        if (favoriteMapper.hasFavorite(user.getId(), courseId) != null) {
            return 2;
        }
        favoriteMapper.insert(user.getId(), courseId);
        return 0;
    }

    public int unFavorite(HttpServletRequest request, HttpServletResponse response, Long courseId) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return 1;
        }
        if (favoriteMapper.hasFavorite(user.getId(), courseId) == null) {
            return 2;
        }
        favoriteMapper.delete(user.getId(), courseId);
        return 0;
    }

    public List<Course> getFavorite(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return null;
        }
        List<Favorite> favorites = favoriteMapper.selectByUserId(user.getId());
        List<Course> courses = new ArrayList<>();
        favorites.forEach((favorite -> courses.add(favorite.getCourse())));
        return courses;
    }

    public Reply getUploaded(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return new Reply("查询教师上传的课程").error(1, "您尚未登录");
        }
        Teacher teacher = teacherMapper.selectByUserId(user.getId());
        if (teacher == null) {
            return new Reply("查询教师上传的课程").error(2, "未找到用户");
        }
        List<Course> courses = courseMapper.selectByTeacherId(teacher.getId());

        return new Reply("查询教师上传的课程").ok(0, "成功").put("courses", courses);
    }

    public Reply uploadAudio(HttpServletRequest request, String audioName, String audioLabel) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            // 用户未登录
            return new Reply("教师上传音频").ok(1, "您尚未登录");
        }
        int identity = user.getIdentity();
        if (identity == 1) {
            // 用户不是教师
            return new Reply("教师上传音频").error(2, "用户不是教师");
        }
        Teacher teacher = teacherMapper.selectByUserId(user.getId());
        Audio audio = new Audio();
        audio.setAudioName(audioName);
        audio.setAudioLabel(audioLabel);
        audio.setTeacher(teacher);
        audioMapper.insert(audio);
        Long audioId = audio.getId();
        if (audioId == null) {
            // 新建课程失败
            return new Reply("教师上传音频").error(3, "上传失败");
        }
        return new Reply("教师上传音频").ok(0, "成功").put("audioId", audioId);
    }

    public List<Audio> getAudio(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null || user.getIdentity() != 0) {
            // 用户未登录或不是教师
            return null;
        }
        Teacher teacher = teacherMapper.selectByUserId(user.getId());
        return audioMapper.selectByTeacherId(teacher.getId());

    }

    public Audio getAudioById(HttpServletRequest request, HttpServletResponse response, Long audioId) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null || user.getIdentity() != 0) {
            // 用户未登录或不是教师
            return null;
        }
        return audioMapper.selectById(audioId);
    }

    public Appearance getAppearanceById(HttpServletRequest request, HttpServletResponse response, Long appearanceId) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null || user.getIdentity() != 0) {
            // 用户未登录或不是教师
            return null;
        }
        return appearanceMapper.selectById(appearanceId);
    }

    public int deleteAudio(Long audioId) {
        Audio audioToDelete = audioMapper.selectById(audioId);
        if (audioToDelete == null) {
            // 未查询到该音频
            return 1;
        }
        String audioName = audioToDelete.getAudioName();
        File file = new File(uploadDir + audioName);
        if (!file.exists()) {
            //文件不存在！
            return 2;
        } else {
            boolean flag = file.delete();
            if (!flag) {
                // 音频删除失败
                return 3;
            }
        }
        audioMapper.deleteById(audioId);
        return 0;
    }

    public Reply uploadAppearance(HttpServletRequest request, String appearanceName, String appearanceLabel, String coverName) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            // 用户未登录
            return new Reply("教师上传外形").ok(1, "您尚未登录");
        }
        int identity = user.getIdentity();
        if (identity == 1) {
            // 用户不是教师
            return new Reply("教师上传外形").error(2, "用户不是教师");
        }
        Teacher teacher = teacherMapper.selectByUserId(user.getId());
        Appearance appearance = new Appearance();
        appearance.setTeacher(teacher);
        appearance.setAppearanceLabel(appearanceLabel);
        appearance.setAppearanceName(appearanceName);
        appearance.setCoverName(coverName);
        appearanceMapper.insert(appearance);
        Long appearanceId = appearance.getId();
        if (appearanceId == null) {
            // 外形上传失败
            return new Reply("教师上传外形").error(3, "上传失败");
        }
        return new Reply("教师上传外形").ok(0, "成功").put("appearanceId", appearanceId);
    }

    public List<Appearance> getAppearance(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null || user.getIdentity() != 0) {
            // 用户未登录或不是教师
            return null;
        }
        Teacher teacher = teacherMapper.selectByUserId(user.getId());
        return appearanceMapper.selectByTeacherId(teacher.getId());

    }

    public int deleteAppearance(Long appearanceId) {
        Appearance appearance = appearanceMapper.selectById(appearanceId);
        if (appearance == null) {
            // 未查询到该外形
            return 1;
        }
        String appearanceName = appearance.getAppearanceName();
        File file = new File(uploadDir + appearanceName);
        if (!file.exists()) {
            //文件不存在！
            return 2;
        } else {
            boolean flag = file.delete();
            if (!flag) {
                // 外形删除失败
                return 3;
            }
        }
        appearanceMapper.deleteById(appearanceId);
        return 0;
    }
}

